package ldh.im.fxbase.util;

import ldh.im.fxbase.dao.ImGroupDao;
import ldh.im.fxbase.dao.ImUserDao;
import ldh.im.fxbase.data.pojo.ImGroup;
import ldh.im.fxbase.data.pojo.ImUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class ImCacheFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImCacheFactory.class);

    public static final ImCacheFactory instance = new ImCacheFactory();

    private Map<String, ImUser> userMap = new ConcurrentHashMap<>();
    private Map<Long, ImGroup> imGroupMap = new ConcurrentHashMap<>();
    private Map<String, ImGroup> imGroupCodeMap = new ConcurrentHashMap<>();
//    private Map<Long, Integer> hotMessageTotalMap = new ConcurrentHashMap<>(); // 热点数据
    private Map<String, Boolean> cacheStampMap = new ConcurrentHashMap<>();

    private ImUserDao imUserDao = BeanFactory.getInstance().getBean(ImUserDao.class);
    private ImGroupDao imGroupDao = BeanFactory.getInstance().getBean(ImGroupDao.class);
    private boolean isLoadingUser = false;

    public static ImCacheFactory getInstance() {
        return instance;
    }

    private ImCacheFactory() {}

    public void loadAllUsers() {
        LOGGER.info("load all users");
        try {
            if (!this.isLoadingUser) {
                List<ImUser> users = imUserDao.getDefaultUsers();
                users.forEach(u-> userMap.put(u.getUserId(), u));
                isLoadingUser = true;
            }
        } catch (Exception e) {
            LOGGER.info("加载用户失败", e);
        }
    }

    public void putUser(String userId, ImUser imUser) {
        userMap.put(userId, imUser);
    }

    public ImUser getUser(String userId) {
        ImUser imUser = userMap.get(userId);
        if (imUser == null) {
            synchronized (ImCacheFactory.class) {
                if (imUser == null) {
                    try {
                        imUser = imUserDao.getUserById(userId);
                        if (imUser != null) {
                            userMap.put(userId, imUser);
                        } else {
                            LOGGER.error("用户不存在, userId: {}", userId);
                        }
                    } catch (Exception e) {
                        LOGGER.error("加载用户失败, userId: {}", userId);
                    }
                }
            }
        }
        return userMap.get(userId);
    }

    public List<ImUser> getAllUsers() {
        return userMap.values().stream().map(u->u).collect(Collectors.toList());
    }

    public void putImGroup(Long groupId, ImGroup imGroup) {
        imGroupMap.put(groupId, imGroup);
        imGroupCodeMap.put(imGroup.getCode(), imGroup);
    }

    public ImGroup getImGroup(Long groupId) {
        return imGroupMap.get(groupId);
    }

    public ImGroup getImGroup(String currentUserId, String groupCode) {
        ImUser imUser = this.getUser(currentUserId);
        String groupKey = imUser.getId() + "_" + groupCode;
        ImGroup imGroup = imGroupCodeMap.get(groupKey);
        if (imGroup == null) {
            synchronized (ImCacheFactory.class) {
                if (imGroup == null) {
                    try {
                        imGroup = imGroupDao.getByUserIdAndId(currentUserId, groupCode);
                        if (imGroup != null) {
                            putImGroup(imGroup.getId(), imGroup);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        return imGroup;
    }

//    public void setHotMessage(Long sessionId, int value) {
//        if (value < 0) return;
//        hotMessageTotalMap.put(sessionId, value);
//    }
//
//    public void incHotMessage(Long sessionId, int value) {
//        if (value < 1) return;
//        Integer total = getHotMessage(sessionId);
//        total = total == null ? 0  : total;
//        total += value;
//        hotMessageTotalMap.put(sessionId, total);
//    }
//
//    public void decHotMessage(Long sessionId, int value) {
//        if (value < 1) return;
//        Integer total = getHotMessage(sessionId);
//        total = total == null ? 0  : total;
//        total -= value;
//        hotMessageTotalMap.put(sessionId, total);
//    }
//
//    public void cleanHotMessage(Long sessionId) {
//        hotMessageTotalMap.remove(sessionId);
//    }
//
//    public Integer getHotMessage(Long groupId) {
//        return hotMessageTotalMap.get(groupId);
//    }
//
//    public Map<Long, Integer> getAllHotMessage() {
//        return hotMessageTotalMap;
//    }

    public void putStamp(String key, boolean value) {
        cacheStampMap.put(key, value);
    }

    public Boolean isCache(String key) {
        return cacheStampMap.get(key) != null && cacheStampMap.get(key).booleanValue();
    }
}
